package com.itbaizhan.listener;

import com.alibaba.fastjson.JSON;
import com.itbaizhan.domain.TxLog;
import com.itbaizhan.mapper.TxLogMapper;
import com.itbaizhan.service.OrderService;
import com.itbaizhan.tx.TxMessage;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author spf
 * @date 2024/4/23
 * @time 9:37
 */
@RocketMQTransactionListener
@Component
public class OrderTxMessageListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private TxLogMapper txLogMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            String messageString = new String((byte[])message.getPayload());
            TxMessage txMessage = JSON.parseObject(messageString, TxMessage.class);

            // 执行本地事务
            orderService.submitOrderOrSaveTx(txMessage);

            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 回查事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageString = new String((byte[])message.getPayload());
        TxMessage txMessage = JSON.parseObject(messageString, TxMessage.class);

        // 订单微服务查询本地事务
        TxLog txLog = txLogMapper.selectById(txMessage.getTxNo());
        if(txLog !=null){
            return RocketMQLocalTransactionState.COMMIT;
        }

        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
